package br.ufrrj.im.redes.view;


import javax.swing.JFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JButton;
import javax.swing.SwingConstants;

import br.ufrrj.im.redes.logic.GameLogic;
import br.ufrrj.im.redes.model.User;
import br.ufrrj.im.redes.util.Constants;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;


public class WaitStartGameWindow {

	private JFrame frame;
	
	private User user;
	private String server_IP;
	
	private GameLogic gameLogic;
	
	private boolean statusConnection;
	
	private Thread waitStartGameThread;
	

	public void showWindow(){
		this.frame.setVisible(true);
	}
	
	private void startGame(){

		if (this.user.getMode() == Constants.GAMER_MODE){
			GamerWindow gamer = new GamerWindow(gameLogic, Constants.ATTEMPTS_GAME);
			gamer.showWindow();
			this.frame.setVisible(false);
		}
		else{
			SpectatorWindow spectator = new SpectatorWindow();
			spectator.showWindow();
			this.frame.setVisible(false);
		}
		
	
	}
	
	@SuppressWarnings("deprecation")
	private void exit(){		
		
		int msgBox = JOptionPane.NO_OPTION;
		
		if(!statusConnection){
			JOptionPane.showMessageDialog(frame, "Conexão estabelecida com servidor foi perdida.", "Perda de conexão com o servidor", JOptionPane.INFORMATION_MESSAGE);
			
			disconnectGame();
			
			frame.setVisible(false);
			LoginClientWindow loginWindow = new LoginClientWindow(this.user.getName(), this.server_IP);
			loginWindow.showWindow();
			waitStartGameThread.stop();
			
		}
		else if (statusConnection){
			msgBox = JOptionPane.showConfirmDialog(frame, "Você realmente deseja sair? \nSua conexão com o servidor será encerrada.", "Sair", JOptionPane.YES_NO_OPTION);
			
			// Sim ou não
			if (msgBox == JOptionPane.YES_OPTION){
				
				disconnectGame();
				
				frame.setVisible(false);
				LoginClientWindow loginWindow = new LoginClientWindow(this.user.getName(), this.server_IP);
				loginWindow.showWindow();
				waitStartGameThread.stop();
			}

		}
	}
	
	private void disconnectGame(){
		
		try {
			//gameLogic.comunicateServerTheEndConnection();
			gameLogic.closeConnectionsAndStreams();	
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
	}

	/**
	 * Create the application.
	 */
	public WaitStartGameWindow(User user) {
		this.user = user;
		this.statusConnection = true;
		
		initialize();
		
		try {
			
			gameLogic = new GameLogic(user);
			
			waitStartGameThread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					int rangePrime = Constants.INVALID_RANGE_PRIME;
					
					
					try {
						
						do {
							
							rangePrime = gameLogic.getStartGame();
							
						}while ((rangePrime == Constants.INVALID_RANGE_PRIME) && (gameLogic.getStatusConnection()));

						
						//Se a conexão do jogo ainda estiver estabelecida, então o jogo foi iniciado
						if((rangePrime != Constants.INVALID_RANGE_PRIME) && (gameLogic.getStatusConnection())){
							
							//inicia o jogo
							startGame();
							gameLogic.setRangePrime(rangePrime);
							System.out.println("WaitStartGameWindow:: start game");
							
						}
						else{
							
							gameLogic.closeConnectionsAndStreams();
							statusConnection = false;
							System.out.println("WaitStartGameWindow:: closed connection");
							exit();
						}
										
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						JOptionPane.showMessageDialog(frame, "00 " +  e.toString(), "Erro", JOptionPane.ERROR_MESSAGE);
						statusConnection = false;
						exit();
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						JOptionPane.showMessageDialog(frame, "10 " + e.toString(), "Erro", JOptionPane.ERROR_MESSAGE);
						statusConnection = false;
						exit();
					}
							
				}
			});
			
			
			waitStartGameThread.start();
			
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			JOptionPane.showMessageDialog(frame, "11 " + e1.toString(), "Erro", JOptionPane.ERROR_MESSAGE);
			statusConnection = false;
			exit();
		}
		
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				
				exit();
				
			}
		});
		frame.setBounds(100, 100, 419, 210);
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		
		JLabel lblNewLabel = new JLabel("<html>Conexão com o servidor estabelecida.<br>Aguardando o leiloeiro para iniciar a partida...</html>");
		lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		
		JProgressBar progressBar = new JProgressBar();
		progressBar.setIndeterminate(true);
		
		JButton btnDesconectar = new JButton("Desconectar");
		btnDesconectar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				exit();
								
			}
		});
		
		btnDesconectar.setMnemonic('D');
		GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addComponent(lblNewLabel, GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
							.addContainerGap())
						.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
							.addComponent(progressBar, GroupLayout.PREFERRED_SIZE, 324, GroupLayout.PREFERRED_SIZE)
							.addGap(44))
						.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
							.addComponent(btnDesconectar)
							.addGap(143))))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addComponent(lblNewLabel)
					.addGap(34)
					.addComponent(progressBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addGap(32)
					.addComponent(btnDesconectar)
					.addContainerGap(34, Short.MAX_VALUE))
		);
		frame.getContentPane().setLayout(groupLayout);
	}
}
